from fastapi import Request
from pydantic import BaseModel
from tortoise.transactions import atomic, in_transaction

from service import RepositoryService, UserService, CollaboratorService, BookService
from common.result.Result import Result
from common.enum import BaseEnum
from common.const import BaseConstant
from util.redis import Redis
from util.str import Str
from util.log import Log
from util.token import Token
from util.time import Time

class Body(BaseModel):
    shortUri: str

async def DeleteBook(req: Request, body: dict):
    try:
        async with in_transaction() as connection:
            shortUri = body.get('shortUri')
            if Str.isBlank(shortUri):
                Log.error('参数为空，检查参数')
                return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)
            
            token = req.headers.get("token")
            user = await UserService.getUserByToken(token)
            if user == None:
                Log.error('用户不存在')
                return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)
            
            # 获取 book
            book = await BookService.getBookByShortUri(shortUri)
            if book == None:
                Log.error('book 不存在')
                return Result.error(BaseEnum.BOOK_NOT_EXISTS_ERROR)
            
            # 获取 repository
            repository = await RepositoryService.getRepositoryById(book.repository_id)
            if repository == None:
                Log.error('repository 不存在')
                return Result.error(BaseEnum.REPOSITORY_NOT_EXISTS_ERROR)

            # 判断仓库是否允许用户写（只能 协作者 和 创建者 写）
            flag = await RepositoryService.getUserWritePermission(repository, user.id)
            if flag == False:
                Log.error('该 repository 不允许该用户写')
                return Result.error(BaseEnum.REPOSITORY_NO_WRITE_PERMISSION_ERROR)
            
            cnt = await BookService.deleteBookById(book.id)

            # 删除 book 的缓存
            key = BaseConstant.BOOK_KEY % book.short_uri
            Redis.deleteItem(key)

            # 删除 book tree 的缓存
            key = BaseConstant.BOOK_TREE_KEY % repository.short_uri
            Redis.deleteItem(key)
            
            return Result.success(cnt)
    except Exception as e:
        Log.error('删除 book 异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)